import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import userApi, {
  type LoginParamsDatd,
  type UserInfoDate,
} from "@/api/userinfo";
import type { RouteRecordRaw } from "vue-router";

type useUserInfoStoreData = {
  token: string;
  userInfo: UserInfoDate;
  menuRoutes: RouteRecordRaw[];
};

//封装函数初始话数据
function initUserInfo() {
  return {
    routes: [],
    buttons: [],
    roles: [],
    name: "",
    avatar: "",
  };
}

export const useUserInfoStore = defineStore("userInfo", {
  state: (): useUserInfoStoreData => ({
    token: localStorage.getItem("token") || "",
    userInfo:initUserInfo(),
    menuRoutes: staticRoutes, //这个数组（路由数组）生成每一个菜单选项，菜单是根据路由动态生成的
  }),

  actions: {
    async login(loginParams: LoginParamsDatd) {
      try {
        const res = await userApi.login(loginParams);
        this.token = res.token;
        localStorage.setItem("token", res.token);
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },

    async getInfo() {
      //获取用户信息
      try {
        const res = await userApi.info();
        this.userInfo = res;
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },

    //重置用户信息
    reset() {
      // 删除local中保存的token
      this.token = "";
      //清除本地存储中的token
      localStorage.removeItem("token");
      this.userInfo=Object.assign(this.userInfo,initUserInfo())
    },

    //退出登录

    async logoout() {
      try {
        const res = await userApi.logout();
        //清除用户相关信息
        this.reset();
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },
  },
});
